< previous page page_343 next page >

Page 343
Keeping Track of the Ambient Colors
To fix this potential problem, you have to set the control's colors to match those of its container. First, delete the instance of the sample control you just created, and return to the UserControl window. Next, add the following lines of code to the InitProperties() event procedure:
    UserControl.BackColor = Ambient.BackColor
    UserControl.ForeColor = Ambient.ForeColor
Your control should now be able to match itself to the container's colors. To verify this fact, close the UserControl window so that the control becomes available in the Toolbox. Then draw an instance of the user control on the form. When the new control instance appears, it should be the same color as the form (see Figure 15.2).
0343-01.jpg
Figure 15.2
The 
Ambient object can retrieve information about
the control's container, such as the color properties.
What happens, though, if the users of the control change the background color again? Go ahead and set the BackColor property of the form to another color. When you do, the form immediately changes to match your selection, but the control remains purple. You get this result because you placed code in the InitProperties event but not in the all-important AmbientChanged event.
To demonstrate, add code for this event to the user control now:
Private Sub UserControl_AmbientChanged(PropertyName As String)
    UserControl.BackColor = Ambient.BackColor
    UserControl.ForeColor = Ambient.ForeColor
End Sub
Now, close the UserControl window, and draw an instance of the control on the form. Change the BackColor property values, and this time the control's background color changes as well.
Properties of the Ambient Object
As you have probably guessed, the AmbientChanged event fires when the properties of the Ambient object are changed. The example updates the ForeColor and BackColor properties every time the event is fired, but the PropertyName parameter allows you to determine which property changed.
In addition to the color properties, the Ambient object contains several others. Some of the more important ones are listed in Table 15.1.

 
< previous page page_343 next page >